package com.demo.config.sharding.algorithm;



import org.apache.shardingsphere.sharding.api.sharding.standard.PreciseShardingValue;
import org.apache.shardingsphere.sharding.api.sharding.standard.RangeShardingValue;
import org.apache.shardingsphere.sharding.api.sharding.standard.StandardShardingAlgorithm;
import org.springframework.context.annotation.Configuration;

import java.util.Collection;

/**
 * 按照取模分库
 * @Author: shenyang
 * @CreateTime: 2022-11-22  14:32
 * @Description: TODO
 * @Version: 1.0
 */
@Configuration
public class ShardingDatabaseModuloAlgorithm<T extends Comparable<?>> implements StandardShardingAlgorithm<T> {


    /**
     *  当条件为单个值时进入
     */
    @Override
    public String doSharding(Collection<String> collection, PreciseShardingValue<T> preciseShardingValue) {
        Long value = Long.valueOf(preciseShardingValue.getValue().toString());
        Long mo = (value % collection.size() + 1);
        String db_suffix;
        if (mo < 10) {
            db_suffix = "_0" + mo;
        } else {
            db_suffix = "_" + mo;
        }

        for (String each : collection) {
            if (each.endsWith(db_suffix)) {
                return each;
            }
        }

        throw new UnsupportedOperationException("不支持的库" + value);
    }

    /**
     * 当条件为范围时进入
     */
    @Override
    public Collection<String> doSharding(Collection<String> collection, RangeShardingValue<T> rangeShardingValue) {
        return collection;
    }

    @Override
    public void init() {
        System.out.println("进入init");
    }

    /**
     * 算法类型名称，可自定义
     */
    @Override
    public String getType() {
        return "STANDDARD_DB_MODULO";
    }
}

